import React, {Component} from 'react';
import {render} from 'react-dom';
import ThemeProvider from 'material-ui/styles/MuiThemeProvider';
import createTheme from 'material-ui/styles/createMuiTheme';
import createStore from 'redux/lib/createStore';
import Provider from 'react-redux/lib/components/Provider';
import connect from 'react-redux/lib/connect/connect';
import Router from 'react-router-dom/HashRouter';
import teal from 'material-ui/colors/teal';
import red from 'material-ui/colors/red';

import App from './app';
import reducer, {actionCreators} from './reducer';

const store = createStore(reducer);
const theme = createTheme({
  palette: {
    primary: red,
    secondary: teal
  },
  overrides: {
    MuiTypography: {
      title: {
        flexGrow: 1,
      },
      body1: {
        fontSize: '.95rem',
        lineHeight: '1.75em'
      },
      headline: {
        lineHeight: '1.75em'
      }
    }
  }
});

@connect(
  ({confirm}) => ({confirm}),
  {...actionCreators}
)
class RouterWithDialog extends Component{
  handler = null;

  componentWillReceiveProps(nextProps) {
    if (typeof this.handler === 'function') {
      const {closePayload, target, open} = nextProps.confirm;
      if (!open
        && target === 'router'
        && typeof closePayload !== 'undefined'
      ) {
        this.handler(closePayload);
        this.handler = undefined;
        nextProps.resolveConfirm();
      }
    }
  }

  handleConfirmation = (message, handler) => {
    this.handler = handler;

    this.props.openConfirm({
      message,
      openType: 'WARN',
      target: 'router',
      confirmPayload: true,
      cancelPayload: false
    })
  }

  shouldComponentUpdate() {
    return false;
  }


  render() {
    return (
      <Router getUserConfirmation={this.handleConfirmation}>
        {this.props.children}
      </Router>
    )
  }

}

render(
  <ThemeProvider theme={theme}>
    <Provider store={store}>
      <RouterWithDialog>
        <App/>
      </RouterWithDialog>
    </Provider>
  </ThemeProvider>,
  document.getElementById('app-root')
);